<template>
    <el-dialog v-model="dialogVisible" :title="`${typeName}长期保行业 `" width="820px" :destroy-on-close="true">
        <div class="fc-main container fs-12">
            <div class="flex gap-16px">
                <div class="flex items-center flex-3">
                    <div class="flex-l">行业名称</div>
                    <div class="flex-r flex-1">
                        <el-input v-model="indrustryData.name" class="w-full" placeholder="请输入行业名称" />
                    </div>
                </div>
                <div class="flex-2"></div>
            </div>
            <div v-for="(i, index) in indrustryData.occupationList" :key="index" class="flex gap-16px">
                <div class="item-left flex-3">
                    <div class="flex items-center mg-t-40" @click="i.toggle=!i.toggle">
                        <div class="flex-l">
                            <el-icon v-show="!i.toggle" class="pointer">
                                <CaretBottom />
                            </el-icon>

                            <el-icon v-show="i.toggle" class="pointer">
                                <CaretTop />
                            </el-icon> 行业工种</div>
                        <div class="flex-r flex-1 relative">
                            <div class="name">工种名称</div>
                            <el-input v-model="i.name" class="w-full" placeholder="请输入行业工种名称" />
                        </div>
                    </div>
                    <el-collapse-transition>
                        <div class="flex" v-show="i.toggle || indrustryData.occupationList.length === 1">
                            <div class="flex-l flex flex-jc-c">
                                <div class="border"></div>
                            </div>
                            <div class="flex-r flex-1">
                                <div v-for="(item, idx) in i.insurCompanyOccupationList" :key="idx"
                                    class="flex items-center mg-t-40 set-border">
                                    <div class="left flex-1 fc-primary fs-14">
                                        {{ item.insurCompanyName }}
                                    </div>
                                    <div class="right flex-3 relative">
                                        <div class="name">
                                            原（保司）工种名称
                                        </div>
                                        <el-input v-model="item.originName" class="w-full" placeholder="请输入原（保司）工种名称" />
                                    </div>
                                </div>
                                <div class="flex items-center mg-t-40 set-border">
                                    <div class="left w-70 fc-primary flex gap-16px">
                                        <el-button v-if="index === indrustryData.occupationList.length - 1" icon="Document"
                                            @click="handleAdd">新增行业工种</el-button>
                                        <el-button v-if="indrustryData.occupationList.length !== 1" icon="Delete"
                                            @click="handleDelete(index)">删除行业工种</el-button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </el-collapse-transition>
                </div>
                <div class="item-right flex-2">
                    <div class="item-left flex-1">
                        <div class="flex items-center mg-t-40">
                            <div class="flex-r flex-1 relative">
                                <div class="name">风险等级</div>
                                <el-select v-model="i.level" class="w-full" placeholder="请选择风险等级">
                                    <el-option v-for="item in levelOptions" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </div>
                        </div>
                        <el-collapse-transition>
                            <div class="flex" v-show="i.toggle || indrustryData.occupationList.length === 1">
                                <div class="flex-r flex-1">
                                    <div class="flex items-center mg-t-40 gap-16px"
                                        v-for="(item, idx) in i.insurCompanyOccupationList" :key="idx">
                                        <div class="right flex-1 relative">
                                            <div class="name">
                                                工种编号
                                            </div>
                                            <el-input v-model="item.code" class="w-full" placeholder="请输工种编号" />
                                        </div>
                                        <div class="right flex-1 relative">
                                            <div class="name">
                                                原风险等级
                                            </div>
                                            <el-select v-model="item.originLevel" class="w-full" placeholder="请选择风险等级">
                                                <el-option v-for="j in levelOptions" :key="j.value" :label="j.label"
                                                    :value="j.value" />
                                            </el-select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </el-collapse-transition>
                    </div>
                </div>
            </div>
        </div>
        <template #footer>
            <div class="flex flex-jc-c">
                <div class="flex">
                    <el-button type="primary" @click="submit">
                        确定
                    </el-button>
                    <el-button @click="dialogVisible = false">取消</el-button>
                </div>
            </div>
        </template>
    </el-dialog>
</template>
<script setup>
import { ref, watch, computed, onMounted, onActivated} from 'vue'
import { cloneDeep } from 'lodash'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getInsureCompanyList, addIndustry, updateIndustry, getDchemeList } from 'api/insure/longTerm.ts'

const props = defineProps({
    show: {
        type: Boolean,
        default: false
    },
    type: {
        type: String,
        default: 'add'
    },
    curItem: {
        type: Object,
        default() {
            return {}
        }
    }
})

const emits = defineEmits(['update:show', 'update:curItem', 'success'])

const dialogVisible = ref(false)

const basicInfo = {
    bankName: {
        label: '保司编码',
        prop: 'bankName',
        disabled: true,
        type: 'input',
        placeholder: '请输入保司编码',
        inputType: 'text',
        value: ''
    },
    date: {
        label: '生效年月',
        prop: 'date',
        type: 'date',
        placeholder: '请输入保司编码',
        dateType: 'month',
        value: ''
    },
}

const typeName = computed(() => {
    return props.type === 'add' ? '新增' : '编辑'
})

watch(() => props.show, (newval) => {
    dialogVisible.value = newval
})

watch(dialogVisible, (newval) => {
    emits('update:show', newval)
    if (newval && props.type === 'add') {
        indrustryData.value.name = ''
        indrustryData.value.occupationList = []
        indrustryData.value.occupationList.push(createData())
    }
    if (!newval) {
        emits('update:curItem', {})
    }
})

const companyList = ref([])

const indrustryData = ref(
    {
        name: '',
        occupationList: []
    }
)

const levelOptions = ref([
    { label: '1类', value: '1' },
    { label: '2类', value: '2' },
    { label: '3类', value: '3' },
    { label: '4类', value: '4' },
    { label: '5类', value: '5' },
    { label: '6类', value: '6' }
])

const getList = () => {
    getInsureCompanyList(
        {
            type: 2,
            pageSize: 100
        }
    ).then(res => {
        companyList.value = res.rows
        indrustryData.value.occupationList.push(createData())
    })
}

const createData = () => {
    const insurCompanyOccupationList = []
    companyList.value.forEach(i => {
        insurCompanyOccupationList.push({
            insurCompany: i.code,
            insurCompanyName: i.name,
            originName: '',
            code: '',
            originLevel: '',
        })
    })
    return {
        name: '',
        level: '',
        toggle: false,
        insurCompanyOccupationList: insurCompanyOccupationList
    }
}

const handleAdd = () => {
    indrustryData.value.occupationList.push(createData())
}

const handleDelete = (index) => {
    ElMessageBox.confirm(
        '此操作将永久删除该工种，将会导致部分企业投保找不到工种，和续保失败，最后提交编辑内容将生效，是否继续?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            indrustryData.value.occupationList.splice(index, 1)
        })
        .catch(() => {

        })
}

const submit = () => {
    if (!indrustryData.value.name?.trim()) {
        ElMessage.error({
            message: '行业名称不能为空'
        })
        return
    }
    if (indrustryData.value.occupationList.some(i => !i.name?.trim())) {
        ElMessage.error({
            message: '工种名称不能为空'
        })
        return
    }
    if (indrustryData.value.occupationList.some(i => !i.level?.trim())) {
        ElMessage.error({
            message: '风险等级不能为空'
        })
        return
    }
    const queryData = cloneDeep(indrustryData.value)

    queryData.occupationList.forEach(i => {
        i.insurCompanyOccupationList = i.insurCompanyOccupationList.filter(i => i.code?.trim() && i.originLevel?.trim() && i.originName?.trim())
    })

    if (props.type === 'add') {
        addIndustry(queryData).then(res => {
            ElMessage.success({
                message: '新增成功'
            })
            emits('success')
            dialogVisible.value = false
        })
    } else {
        queryData.id = props.curItem.id
        updateIndustry(queryData).then(res => {
            ElMessage.success({
                message: '编辑成功'
            })
            emits('success')
            dialogVisible.value = false
        })
    }
}

watch(() => props.curItem, (newval) => {
    if (props.type === 'update' && Object.keys(newval)?.length) {
        indrustryData.value.name = newval.name
        indrustryData.value.occupationList = []
        newval.occupationList.forEach(i => {
            const tempData = createData()
            tempData.name = i.name
            tempData.level = i.level
            tempData.id = i.id
            tempData.periodIndustryId = i.periodIndustryId
            i.insurCompanyOccupationList.forEach(k => {
                const idx = tempData.insurCompanyOccupationList.findIndex(j => j.insurCompany === k.insurCompany)
                if (idx !== -1) {
                    tempData.insurCompanyOccupationList[idx].originName = k.originName
                    tempData.insurCompanyOccupationList[idx].code = k.code
                    tempData.insurCompanyOccupationList[idx].originLevel = k.originLevel
                }
            })
            indrustryData.value.occupationList.push(tempData)
        })
    }

}, {
    immediate: true,
    deep: true
})

onMounted(() => {
    getList()
})
onActivated(() => {
    getList()
})
</script>
<style lang="scss" scoped>
.flex-l {
    width: 80px;
}

.relative {
    position: relative;
}

.name {
    position: absolute;
    top: -22px;
    left: 0;
}

.w-70 {
    width: 70px;
}

.border {
    border-left: 1px solid #EAEAEF;
    height: calc(100% - 15px);
    margin-left: -25px;
}

.set-border {
    position: relative;
}

.set-border::before {
    content: '';
    border-top: 1px solid #EAEAEF;
    width: 40px;
    position: absolute;
    left: -53px;
}

.container {
    max-height: 600px;
    overflow: auto;
}
</style>
